package com.longlong.config.security.handler;

import com.longlong.config.security.service.UserDetailsServiceImpl;
import com.longlong.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token校验
 * 在接口访问前校验
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    /**
     * token工具类
     */
    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;


    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 请求前获取请求头信息token
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1.获取token
        String header = request.getHeader(tokenHeader);

        //2.判断token是否存在
        if(header != null && header.startsWith(tokenHead)){
            //拿到token主体
            String token = header.substring(tokenHead.length());
            //根据Token获取用户名
            String username = tokenUtil.getUsernameByToken(token);
            //3.token存在，但是没有登录信息

            if(token != null && SecurityContextHolder.getContext().getAuthentication() == null && username!=null){
                //没有登录信息，直接登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                //判断token是否有效
                if(!tokenUtil.isException(token) && username.equals(userDetails.getUsername())){
                    //刷新security
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }

        //过滤放行
        filterChain.doFilter(request,response);

    }
}






















